<template>
  <div class="h-full bg-gray-50 p-4 overflow-y-auto">
    <h2 class="text-lg font-semibold mb-4">数据源管理</h2>
    
    <el-button type="primary" size="small" @click="showAddDialog = true" class="mb-4">
      添加数据源
    </el-button>

    <div v-if="!store.dataSources.length" class="text-center text-gray-400 py-8">
      <el-icon size="32" class="mb-2"><DataLine /></el-icon>
      <p>暂无数据源，点击添加按钮创建</p>
    </div>

    <el-table :data="store.dataSources" size="small" class="w-full">
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="type" label="类型">
        <template #default="{ row }">
          <el-tag :type="getTypeTag(row.type)">{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="editDataSource(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteDataSource(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑数据源对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingDataSource ? '编辑数据源' : '添加数据源'"
      width="500px"
    >
      <el-form :model="formData" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="formData.name" placeholder="数据源名称" />
        </el-form-item>

        <el-form-item label="类型" required>
          <el-select v-model="formData.type" placeholder="选择类型">
            <el-option value="static" label="静态数据" />
            <el-option value="api" label="API接口" />
            <el-option value="database" label="数据库" />
          </el-select>
        </el-form-item>

        <template v-if="formData.type === 'static'">
          <el-form-item label="数据">
            <el-button @click="addStaticItem">添加项</el-button>
            <div v-for="(item, index) in formData.config.items" :key="index" class="flex gap-2 mb-2">
              <el-input v-model="item.label" placeholder="标签" />
              <el-input v-model="item.value" placeholder="值" />
              <el-button @click="removeStaticItem(index)" type="danger">删除</el-button>
            </div>
          </el-form-item>
        </template>

        <template v-else-if="formData.type === 'api'">
          <el-form-item label="API地址" required>
            <el-input v-model="formData.config.url" placeholder="https://api.example.com/data" />
          </el-form-item>
          <el-form-item label="请求方法">
            <el-select v-model="formData.config.method">
              <el-option value="GET" />
              <el-option value="POST" />
            </el-select>
          </el-form-item>
        </template>

        <template v-else-if="formData.type === 'database'">
          <el-form-item label="连接字符串">
            <el-input v-model="formData.config.connectionString" placeholder="数据库连接字符串" />
          </el-form-item>
          <el-form-item label="查询SQL">
            <el-input v-model="formData.config.query" type="textarea" rows="3" />
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveDataSource">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { useDesignerStore } from '@/store'
import type { DataSource } from '@/types'

const { store, addDataSource } = useDesignerStore()

const showAddDialog = ref(false)
const editingDataSource = ref<DataSource | null>(null)

const formData = reactive({
  id: '',
  name: '',
  type: 'static' as const,
  config: {
    items: [{ label: '', value: '' }],
    url: '',
    method: 'GET',
    connectionString: '',
    query: ''
  },
  data: []
})

watch(() => formData.type, (newType) => {
  // 重置配置当类型改变时
  formData.config = {
    items: newType === 'static' ? [{ label: '', value: '' }] : [],
    url: '',
    method: 'GET',
    connectionString: '',
    query: ''
  }
})

const getTypeTag = (type: string) => {
  const typeMap: { [key: string]: string } = {
    static: 'success',
    api: 'warning',
    database: 'danger'
  }
  return typeMap[type] || 'info'
}

const addStaticItem = () => {
  formData.config.items.push({ label: '', value: '' })
}

const removeStaticItem = (index: number) => {
  formData.config.items.splice(index, 1)
}

const editDataSource = (dataSource: DataSource) => {
  editingDataSource.value = dataSource
  Object.assign(formData, dataSource)
  showAddDialog.value = true
}

const saveDataSource = () => {
  if (!formData.name) {
    ElMessage.error('请输入数据源名称')
    return
  }

  const dataSource: DataSource = {
    id: editingDataSource.value?.id || Math.random().toString(36).substr(2, 9),
    name: formData.name,
    type: formData.type,
    config: { ...formData.config },
    data: []
  }

  addDataSource(dataSource)
  showAddDialog.value = false
  resetForm()
}

const deleteDataSource = (id: string) => {
  const index = store.dataSources.findIndex(ds => ds.id === id)
  if (index > -1) {
    store.dataSources.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

const resetForm = () => {
  editingDataSource.value = null
  Object.assign(formData, {
    id: '',
    name: '',
    type: 'static',
    config: {
      items: [{ label: '', value: '' }],
      url: '',
      method: 'GET',
      connectionString: '',
      query: ''
    },
    data: []
  })
}
</script>